package com.hw.utils.forkjoinpool;

import java.util.concurrent.RecursiveTask;

/**
 * @program: hwUtils
 * @description:
 * @author: hewei
 * @date: 2023-03-16 14:05
 * 有返回值的迭代任务：计算 start~end 范围内数值的和
 **/

public class RecursiveTaskWorker extends RecursiveTask<Integer> {

    private static final int step = 10;

    private int start;
    private int end;

    public RecursiveTaskWorker(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - start) < step){
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum+=i;
            }
            System.out.println(Thread.currentThread().getName()+" 计算结果："+sum);
            return sum;
        }else {
            int middle=(start+end)/2;
            RecursiveTaskWorker left=new RecursiveTaskWorker(start,middle);
            RecursiveTaskWorker right=new RecursiveTaskWorker(middle,end);
            left.fork();
            right.fork();
            return left.join()+right.join();
        }
    }
}
